package ae.pcfc.cldos.online.web.services.interceptors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import ae.pcfc.cldos.online.web.services.request.beans.RequestVariablesBean;

public class RequestVariablesInterceptor extends HandlerInterceptorAdapter {

	private RequestVariablesBean requestVariablesBean;
	
	public void setRequestVariablesBean(
			RequestVariablesBean requestVariablesBean) {
		this.requestVariablesBean = requestVariablesBean;
	}
	
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		
		requestVariablesBean.setContextPath(request.getContextPath());
		
		String requestedHost = request.getHeader("host");
		if(requestedHost!=null && !requestedHost.isEmpty()){
			if(!requestedHost.contains("http://") || !requestedHost.contains("https://")){
				if(request.isSecure()){
					requestedHost = "https://"+requestedHost;
				} else {
					requestedHost = "http://"+requestedHost;
				}
//				if(!requestedHost.endsWith("/"))
//					requestedHost = requestedHost + "/";
			}
			requestVariablesBean.setRequestedHost(requestedHost);
		}
		
		if(RequestVariablesBean.isAjaxRequest(request)){
			requestVariablesBean.setAjaxRequest(true);
		}
		
		return super.preHandle(request, response, handler);
	}
}
